% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
%   This scripts is for deal GLEAM Version3.5 DATA to agree with CLM Output NC file format and coordinate.
%   The GLEAM is 0.25 x 0.25 deg grids, the CLM-Output is 1 x 1 deg.
%   2021-02-25 by Dayon 
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 

% clear everything
clc; clear all

disp(['----------  Script Executes Start at : ',datestr(datetime),'---------- ']);
% read nc data and Var
varName = 'E';  % DayonModf
varNameLong = 'Actual evaporation from GLEAM v3.5a'; % DayonModf
varUnits = 'mm/month';

InPath = '/home/dayon/Downloads/GleamV3.5a';
Infile = [varName,'_1980-2020_GLEAM_v3.5a_MO.nc'];
InPathFile = [InPath, '/', Infile];

varValue = ncread(InPathFile, varName);

% pack the 16 grids with 0.25 deg to 1 cell with 1 deg
DistrLat  = 4*ones(1, 180);
DistrLon  = 4*ones(1, 360);
DistrTim  = 1*ones(1, 492);
E_Cell = mat2cell(varValue, DistrLat, DistrLon, DistrTim);

% sum the 16 grids to 1 grid, except nan grids
varValueR1D = nan(size(E_Cell));
for iLat = 1:180
    for iLon = 1:360
        parfor iT = 1:492
            tempGrid = E_Cell{iLat, iLon, iT};
            tempGridAlign = tempGrid(:);
            % check the number of NaN
            NumNan = sum(isnan(tempGridAlign));
            if  NumNan < 8 
                ECellNonan = tempGridAlign(~isnan(tempGridAlign));
                ECellSum   = sum(ECellNonan)/(16-NumNan);   % the denominator is the (16-NumNan)
            else
                ECellSum = nan;
            end
            varValueR1D(iLat, iLon, iT) = ECellSum;
        end
    end
end

% shift the lon format from [-180, 180] to [0, 360] and shift fomat to CLM output
varValueR1D = circshift(varValueR1D, [0, 180, 0]);
for iT = 1:492
    tmp = varValueR1D(:,:,iT);
    tmp = flip(tmp);
    tmp = tmp';
    TransF(:,:,iT) = tmp;
end
varValueR1D = TransF;

% ==================================================================================
% make nc file
% ==================================================================================

outDir  = '/home/dayon/Downloads/GLEAM/res1D_GLEAM';
outFile = [varName, '_1980-2020_GLEAM_v3.5a_MO_res1D.nc'];
outDirFile = [outDir, '/', outFile];
outid   = netcdf.create(outDirFile, 'CLASSIC_MODEL');

% define dimensions
latdimID  = netcdf.defDim(outid, 'lat',  180);
londimID  = netcdf.defDim(outid, 'lon',  360);
timedimID = netcdf.defDim(outid, 'time', 492);

% define variables
lat_id  = netcdf.defVar(outid, 'lat', 'NC_DOUBLE', latdimID);
lon_id  = netcdf.defVar(outid, 'lon', 'NC_DOUBLE', londimID);
time_id = netcdf.defVar(outid, 'time','NC_DOUBLE', timedimID);
EVar_id = netcdf.defVar(outid, varName,'NC_DOUBLE', [londimID, latdimID, timedimID]);

netcdf.endDef(outid);

% read referent nc file, the time is same
timeRef      = ncread(InPathFile, 'time');

% recalculate the lat and lon gridcell centre point
latr1D = [-89.5:1:89.5]';
lonr1D = [0.5:1:359.5]';

% put variable into nc
netcdf.putVar(outid, lat_id, latr1D);
netcdf.putVar(outid, lon_id, lonr1D);
netcdf.putVar(outid, time_id, timeRef);
netcdf.putVar(outid, EVar_id, varValueR1D);

netcdf.reDef(outid);

% put Attribute into nc
netcdf.putAtt(outid, lat_id, 'standard_name', 'latitude');
netcdf.putAtt(outid, lat_id, 'long_name', 'latitude');
netcdf.putAtt(outid, lat_id, 'units', 'degrees_north');

netcdf.putAtt(outid, lon_id, 'standard_name', 'longitude');
netcdf.putAtt(outid, lon_id, 'long_name', 'longitude');
netcdf.putAtt(outid, lon_id, 'units', 'degrees_east');

netcdf.putAtt(outid, time_id, 'standard_name', 'time');
netcdf.putAtt(outid, time_id, 'long_name', 'time');
netcdf.putAtt(outid, time_id, 'bounds', 'time_bnds');
netcdf.putAtt(outid, time_id, 'units', 'days since 1900-01-01');
netcdf.putAtt(outid, time_id, 'calendar', 'standard');

netcdf.putAtt(outid, EVar_id, 'long_name', varNameLong);
netcdf.putAtt(outid, EVar_id, 'units', varUnits);
netcdf.putAtt(outid, EVar_id, '_FillValue', -999.0);
netcdf.putAtt(outid, EVar_id, 'missing_value', -999.0);

% define global attribution
netcdf.putAtt(outid, netcdf.getConstant('NC_GLOBAL'), 'frequency', 'mon');
netcdf.putAtt(outid, netcdf.getConstant('NC_GLOBAL'), 'Version', '3.5a')
netcdf.putAtt(outid, netcdf.getConstant('NC_GLOBAL'), 'Create_time', datestr(datetime));
netcdf.putAtt(outid, netcdf.getConstant('NC_GLOBAL'), 'E_mail', 'wangdy58@mail2.sysu.edu.cn');

netcdf.close(outid)

disp(['----------   Script Finishes at: ',datestr(datetime),'---------- ']);
